//
//  AuthoritySettingController.m
//  YSSmartHome
//
//  Created by yanghao on 25/05/2017.
//  Copyright © 2017 yahaong. All rights reserved.
//

#import "AuthoritySettingController.h"
#import "YSCommon.h"
#import "AuthoritySettingCellTopView.h"
#import "RoomModel.h"
#import "DataManager.h"
#import "ZTDevice.h"
#import "AuthorityDeviceCell.h"
#import "UIView+HUD.h"

static CGFloat const margin = 5.0f;
@interface AuthoritySettingController ()
<
UICollectionViewDataSource,
UICollectionViewDelegate
>
@property (nullable, nonatomic, strong) UILabel* hintLable;
@property (nullable, nonatomic, strong) UIButton* notSelectedBtn;
@property (nullable, nonatomic, strong) UILabel* notSelectedExplainLable;
@property (nullable, nonatomic, strong) UIButton* selectedBtn;
@property (nullable, nonatomic, strong) UILabel* selectedExplainLable;
@property (nullable, nonatomic, strong) UICollectionViewFlowLayout* flowLayout ;
@property (nullable, nonatomic, strong) UICollectionView* contentView;
@property (nonatomic, strong)NSArray <RoomModel *> *m_roomModels;
@end

@implementation AuthoritySettingController


#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    [self initSubviews];
    [self refreshDeviceName];
    [self.view yh_showLoadingHUD];
    if (self.mobile.length != 0) {
        XAITYPEAPSN apsn = 0x01;
        XAITYPELUID luid = [XAI mobileToLuid:self.mobile];
        __weak typeof(self)wself = self;
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            __strong typeof(wself)sself = wself;
            if (!sself) { return;}
            NSMutableArray* datas = [NSMutableArray array];
            for (ZTDevice* device in kDataManager.deviceListenList) {
                XAITYPEAPSN apsn = device.apsn;
                XAITLV* tlv = [[XAITLV alloc]initWithType:XAI_DATA_TYPE_BIN_APSN bytes:&apsn length:sizeof(apsn)];
                [datas addObject:tlv];
                XAITYPELUID luid = device.luid;
                tlv = [[XAITLV alloc]initWithType:XAI_DATA_TYPE_BIN_LUID bytes:&luid length:sizeof(luid)];
                [datas addObject:tlv];
            }
            NSArray* tlvs =  [kMQTTSessionManager.xai getAuthorityWithApsn:apsn Luid:luid datas:datas];
            if (tlvs.count % 3 != 0) {
                debugLogInfo(@"数据出错");
                dispatch_async(dispatch_get_main_queue(), ^{
                    [sself.view yh_hideAllHUD];
                    [sself.contentView reloadData];
                });
                return;
            }
            __block NSArray *apsnArr = nil;
            __block NSArray *luidArr = nil;
            __block NSArray *isAuthoryArr = nil;
            [tlvs enumerateObjectsUsingBlock:^(id  _Nonnull type, NSUInteger idx, BOOL * _Nonnull stop) {
                NSPredicate *predicate = [NSPredicate predicateWithFormat:@"type = %@", @(XAI_DATA_TYPE_BIN_APSN)];
                apsnArr = [NSArray arrayWithArray:[tlvs filteredArrayUsingPredicate:predicate]];
                predicate = [NSPredicate predicateWithFormat:@"type = %@", @(XAI_DATA_TYPE_BIN_LUID)];
                luidArr = [NSArray arrayWithArray:[tlvs filteredArrayUsingPredicate:predicate]];
                predicate = [NSPredicate predicateWithFormat:@"type = %@", @(XAI_DATA_TYPE_BIN_DIGITAL_UNSIGN)];
                isAuthoryArr = [NSArray arrayWithArray:[tlvs filteredArrayUsingPredicate:predicate]];
            }];
            
            for (int i = 0; i < apsnArr.count; i++) {
                XAITLV* tlv = apsnArr[i];
                XAITYPEAPSN apsn = 0;
                memcpy(&apsn, [tlv getPayloadbyte], sizeof(XAITYPEAPSN));
                apsn = CFSwapInt32(apsn);
                tlv = luidArr[i];
                XAITYPELUID luid = 0;
                memcpy(&luid, [tlv getPayloadbyte], sizeof(XAITYPELUID));
                luid = CFSwapInt64(luid);
                tlv = isAuthoryArr[i];
                uint8_t isAuthory  = 0;
                memcpy(&isAuthory, [tlv getPayloadbyte], sizeof(isAuthory));
                [kDataManager devlistLock];
                for (ZTDevice* device in kDataManager.deviceListenList) {
                    if (device.apsn == apsn && device.luid == luid) {
                        device.isAuthority = isAuthory;
                    }
                }
                [kDataManager devlistUnlock];
                NSLog(@"apsn = %08x luid = %016llx isAuthory = %zd",apsn,luid,isAuthory);
            }
//            for (XAITLV* tlv in tlvs) {
//                if (index % 3 == 0) {
//                    XAITYPEAPSN apsn = 0;
//                    memcpy(&apsn, [tlv getPayloadbyte], sizeof(XAITYPEAPSN));
//                    apsn = CFSwapInt32(apsn);
//                }
//                
//                NSLog(@"%08x",apsn);
//            
//                tlv = tlvs[index++];
//                XAITYPELUID luid = 0;
//                memcpy(&luid, [tlv getPayloadbyte], sizeof(XAITYPELUID));
//                luid = CFSwapInt64(luid);
//                NSLog(@"%016llx",luid);
//                tlv = tlvs[index++];
//                uint8_t isAuthory  = 0;
//                memcpy(&isAuthory, [tlv getPayloadbyte], sizeof(isAuthory));
//                NSLog(@"%zd",isAuthory);
//                if (index == 3) {
//                    index = 0;
//                }
//                [kDataManager devlistLock];
//                for (ZTDevice* device in kDataManager.deviceListenList) {
//                    device.isAuthority = YES;
//                }
//                [kDataManager devlistUnlock];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [sself.view yh_hideAllHUD];
                    [sself.contentView reloadData];
                });
//
//            }
            
        });
    }
}

- (void)getDevicesIsAuthory
{
    XAITYPEAPSN apsn = 0x01;
    XAITYPELUID luid = [XAI mobileToLuid:self.mobile];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSMutableArray* datas = [NSMutableArray array];
        for (ZTDevice* device in kDataManager.deviceListenList) {
            
            XAITYPEAPSN apsn = device.apsn;
            XAITLV* tlv = [[XAITLV alloc]initWithType:XAI_DATA_TYPE_BIN_APSN bytes:&apsn length:sizeof(apsn)];
            [datas addObject:tlv];
            XAITYPELUID luid = device.luid;
            tlv = [[XAITLV alloc]initWithType:XAI_DATA_TYPE_BIN_LUID bytes:&luid length:sizeof(luid)];
            [datas addObject:tlv];
        }
        NSArray* tlvs =  [kMQTTSessionManager.xai getAuthorityWithApsn:apsn Luid:luid datas:datas];
        XAITLV* tlv = tlvs[0];
        XAITYPEAPSN apsn = 0;
        memcpy(&apsn, [tlv getPayloadbyte], sizeof(XAITYPEAPSN));
        apsn = CFSwapInt32(apsn);
        NSLog(@"%08x",apsn);
        
        tlv = tlvs[1];
        XAITYPELUID luid = 0;
        memcpy(&luid, [tlv getPayloadbyte], sizeof(XAITYPELUID));
        luid = CFSwapInt64(luid);
        NSLog(@"%016llx",luid);
        tlv = tlvs[2];
        uint8_t isAuthory  = 0;
        memcpy(&isAuthory, [tlv getPayloadbyte], sizeof(isAuthory));
        NSLog(@"%zd",isAuthory);
    });
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


#pragma mark - event response
- (void)didTappedCommitBtn
{
    [kDataManager devlistLock];
    NSMutableArray* datas = [NSMutableArray array];
    for (ZTDevice* device in kDataManager.deviceListenList) {
        XAITYPEAPSN apsn = device.apsn;
        XAITLV* tlv = [[XAITLV alloc]initWithType:XAI_DATA_TYPE_BIN_APSN bytes:&apsn length:sizeof(apsn)];
        [datas addObject:tlv];
        XAITYPELUID luid = device.luid;
        tlv = [[XAITLV alloc]initWithType:XAI_DATA_TYPE_BIN_LUID bytes:&luid length:sizeof(luid)];
        [datas addObject:tlv];
        uint8_t isAuthory = 3;
        tlv =[[XAITLV alloc]initWithType:XAI_DATA_TYPE_BIN_DIGITAL_UNSIGN bytes:&isAuthory length:sizeof(isAuthory)];
        [datas addObject:tlv];
    }
    XAITYPEAPSN apsn = 0x01;
    XAITYPELUID luid = [XAI mobileToLuid:self.mobile];
    XAIFormatDataCount* formatCount = [[XAIFormatDataCount alloc]init];
    [formatCount addDataType:XAI_DATA_TYPE_BIN_APSN bytes:&apsn length:sizeof(apsn)];
    [formatCount addDataType:XAI_DATA_TYPE_BIN_LUID bytes:&luid length:sizeof(luid)];
    for (XAITLV* tlv in datas)
    {
        [formatCount addDataType:tlv.type bytes:[tlv getPayloadbyte] length:tlv.payloadlen];
    }
    NSArray* tlvs =  [kMQTTSessionManager.xai setAuthorityWithApsn:apsn Luid:luid datas:datas];
    
    [self getDevicesIsAuthory];
}
#pragma mark - UICollectionViewDataSource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
     return self.m_roomModels.count;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (self.m_roomModels.count > 0)
    {
        return self.m_roomModels[section].devices.count;
    }
    return 0;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    AuthorityDeviceCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([self class]) forIndexPath:indexPath];
    cell.device = self.m_roomModels[indexPath.section].devices[indexPath.row];
    return cell;
}


-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *reusableview = nil;
    if (kind == UICollectionElementKindSectionHeader)
    {
        AuthoritySettingCellTopView *header = (AuthoritySettingCellTopView *)[collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeadView" forIndexPath:indexPath];
        header.title = self.m_roomModels[indexPath.section].name;
        reusableview = header;
    }
    return reusableview;
}

#pragma mark - UICollectionViewDelegate

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    ZTDevice* device =  self.m_roomModels[indexPath.section].devices[indexPath.row];
    device.isAuthority = !device.isAuthority;
    [self.contentView reloadData];
}
#pragma mark - private method
- (void)refreshDeviceName
{
    RoomModel *newDevRoom = [[RoomModel alloc]initWithTitle:@"未分房间的设备"];
    NSMutableArray* roomNameLists = [DataManager roomNameLists];
    NSMutableArray* roomDevLists = [NSMutableArray arrayWithCapacity:roomNameLists.count];
    for (NSString* name in roomNameLists) {
        RoomModel *devRoom = [[RoomModel alloc]initWithTitle:name];
        [roomDevLists addObject:devRoom];
    }
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [kDataManager devlistLock];
        for (ZTDevice *dev  in kDataManager.deviceListenList )
        {
            if (dev.name.length == 0 || [[dev getRoomName] isEqualToString:@"unknow"])
            {
                [newDevRoom.devices addObject:dev];
                continue;
            }
            NSString *devRoomName = [dev getRoomName];
            if (devRoomName.length == 0) {
                continue;
            }
            BOOL isFind = false;
            for (RoomModel *model in roomDevLists) {
                if ([model.name isEqualToString:devRoomName]) {
                    [model.devices addObject:dev];
                    isFind = true;
                    break;
                }
            }
            if (!isFind) {
                RoomModel *room = [[RoomModel alloc]initWithTitle:devRoomName];
                [room.devices addObject:dev];
                [roomDevLists addObject:room];
            }
        }
        [kDataManager devlistUnlock];
        if (newDevRoom.devices.count > 0)
        {
            [roomDevLists insertObject:newDevRoom atIndex:0];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            self.m_roomModels = roomDevLists;
            [self.contentView reloadData];
        });
    });
}


- (void)initSubviews
{
    self.navigationItem.title = @"权限设置";
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"提交" style:UIBarButtonItemStylePlain target:self action:@selector(didTappedCommitBtn)];
    self.view.backgroundColor = kBgColor;
    [self.view addSubview:self.hintLable];
    [self.view addSubview:self.notSelectedBtn];
    [self.view addSubview:self.notSelectedExplainLable];
    [self.view addSubview:self.selectedBtn];
    [self.view addSubview:self.selectedExplainLable];
    [self.view addSubview:self.contentView];
    [self layoutPageSubviews];
}

- (void)layoutPageSubviews
{
    [self.hintLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.view).offset(kIphoneSize_Widith(10));
        make.top.trailing.equalTo(self.view);
        make.height.equalTo(kIphoneSize_Height(40));
    }];
    [self.notSelectedBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.view);
        make.top.equalTo(self.hintLable.bottom);
        make.height.equalTo(kIphoneSize_Height(40));
        make.width.equalTo(kIphoneSize_Widith(110));
    }];
    [self.notSelectedExplainLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(self.notSelectedBtn);
        make.leading.equalTo(self.notSelectedBtn.trailing);
        make.trailing.equalTo(self.view);
    }];
    [self.selectedBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.notSelectedBtn);
        make.top.equalTo(self.notSelectedBtn.bottom);
        make.height.equalTo(self.notSelectedBtn);
        make.width.equalTo(kIphoneSize_Widith(90));
    }];
    [self.selectedExplainLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(self.selectedBtn);
        make.leading.equalTo(self.selectedBtn.trailing);
        make.trailing.equalTo(self.view);
    }];
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.selectedBtn.bottom).offset(kIphoneSize_Height(10));
        make.leading.equalTo(self.view);
        make.trailing.equalTo(self.view);
        make.bottom.equalTo(self.view);
    }];
    
}

#pragma mark - getters and setters 
- (UILabel *)hintLable
{
    if (!_hintLable) {
        _hintLable = [[UILabel alloc]init];
        _hintLable.textColor = RGBColor(102, 102, 102);
        _hintLable.text = @"你可在此设置该好友对你的智能设备的控制权限";
        _hintLable.font = [UIFont systemFontOfSize:13];
    }
    return _hintLable;
}
- (UIButton *)notSelectedBtn
{
    if (!_notSelectedBtn) {
        _notSelectedBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_notSelectedBtn setImage:[UIImage imageNamed:@"round_gray"] forState:UIControlStateNormal];
        [_notSelectedBtn setTitle:@"设备未选中" forState:UIControlStateNormal];
        [_notSelectedBtn setTitleColor:RGBColor(102, 102, 102) forState:UIControlStateNormal];
//        _notSelectedBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 10, 0, -10);
//        _notSelectedBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, -10);
        _notSelectedBtn.backgroundColor = [UIColor whiteColor];
        _notSelectedBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    }
    return _notSelectedBtn;
}


- (UIButton *)selectedBtn
{
    if (!_selectedBtn) {
        _selectedBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_selectedBtn setTitle:@"设备选中" forState:UIControlStateNormal];
        [_selectedBtn setImage:[UIImage imageNamed:@"round_red"] forState:UIControlStateNormal];
        [_selectedBtn setTitleColor:RGBColor(102, 102, 102) forState:UIControlStateNormal];
//        _selectedBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 10, 0, -10);
//         _selectedBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, -10);
        _selectedBtn.backgroundColor = [UIColor whiteColor];
        _selectedBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    }
    return _selectedBtn;
}
- (UILabel *)notSelectedExplainLable
{
    if (!_notSelectedExplainLable) {
        _notSelectedExplainLable = [[UILabel alloc]init];
        _notSelectedExplainLable.textColor = RGBColor(239, 75, 58);
        _notSelectedExplainLable.text = @"(只能读取设备状态)";
        _notSelectedExplainLable.backgroundColor = [UIColor whiteColor];
        _notSelectedExplainLable.font = [UIFont systemFontOfSize:13];
    }
    return _notSelectedExplainLable;
}
- (UILabel *)selectedExplainLable
{
    if (!_selectedExplainLable) {
        _selectedExplainLable = [[UILabel alloc]init];
        _selectedExplainLable.textColor = RGBColor(239, 75, 58);
        _selectedExplainLable.text = @"(不仅可读取，也可控制该智能设备状态)";
        _selectedExplainLable.backgroundColor = [UIColor whiteColor];
        _selectedExplainLable.font = [UIFont systemFontOfSize:13];
    }
    return _selectedExplainLable;
}

- (UICollectionViewFlowLayout *)flowLayout
{
    if (!_flowLayout) {
        _flowLayout = [[UICollectionViewFlowLayout alloc]init];
        _flowLayout.minimumLineSpacing = margin;
        _flowLayout.minimumInteritemSpacing = margin;
        CGFloat width = (kScreenWidth - margin * 6) / 3;
        CGFloat height = width * 0.912;
        _flowLayout.itemSize = CGSizeMake(width, height);
        _flowLayout.headerReferenceSize = CGSizeMake(kScreenWidth, kIphoneSize_Height(45));
        [_flowLayout setHeaderReferenceSize: CGSizeMake(kScreenWidth, kIphoneSize_Height(45))];
    }
    return _flowLayout;
}

- (UICollectionView *)contentView
{
    if (!_contentView) {
        _contentView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:self.flowLayout];
        _contentView.contentInset = UIEdgeInsetsMake(0, margin * 2, 0, margin * 2);
        _contentView.backgroundColor = [UIColor whiteColor];
        _contentView.pagingEnabled = YES;
        _contentView.bounces = NO;
        _contentView.delegate = self;
        _contentView.dataSource = self;
        _contentView.showsVerticalScrollIndicator = NO;
        _contentView.showsHorizontalScrollIndicator = NO;
        [_contentView registerClass:[AuthorityDeviceCell class] forCellWithReuseIdentifier:NSStringFromClass([self class])];
        [_contentView registerClass:[AuthoritySettingCellTopView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeadView"];
    }
    return _contentView;
}
@end
